﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace LCA.Community.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static IUnityContainer _container;

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            InitContainer();

            ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
        }

        protected void Application_End(object sender, EventArgs e)
        {
            CleanUp();
        }

        private static void InitContainer()
        {
            if (_container == null) _container = new UnityContainer();
            var unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            _container = _container.LoadConfiguration(unitySection);            
        }

        private static void CleanUp()
        {
            if (Container != null)
            {
                Container.Dispose();
            }
        }

        public static IUnityContainer Container
        {
            get
            {
                return _container;
            }
        }
    }
}